jQuery(document).ready(function(){
	$ = jQuery;
	
	// Add the rating function
	$.fn.extend({
		rating: function(){
			// Activate a number of stars
			var activate = function(no,el){
				el.children('div').removeClass('x');
				for(i=1;i<=no;i++)
				{
					el.children('div:nth-child('+i+')').addClass('x');
				}
			};
			
			// Mouseover event
			$(this).find('.stars > div').mouseover(function(){
				activate($(this).index()+1,$(this).parent());
			});

			$(this).mouseout(function(){
				activate(parseInt($(this).attr('score')),$(this).children('.stars'));
			});
			
			// Change the value
			$(this).find('.stars > div').click(function(e){
				e.preventDefault();
				e.stopPropagation();
				wp_octoms.xform({
					action:'rate_post',
					data:{
						id:$(this).parent().parent().attr('for'),
						vote:$(this).index()+1
					}
				},$(this));
			});
			
			// The social sharing tool
			if(typeof addthis != 'undefined')
			{
				// Get the button
				button = $('.addthis_button_compact',$(this))[0];
				
				// Get the URL
				url = $(button).attr('url');
				// Get the title
				title = $(button).attr('title');
				
				// Add the button
				addthis.button(
					button, 
					{
						ui_hover_direction: -1,
						ui_delay: 400,
						ui_offset_top: 30,
						ui_offset_left: 20
					}, 
					{
						url: url, 
						title: title
					}
				);
			}
			$(this).find('.social a').click(function(e){
				e.preventDefault();
				e.stopPropagation();
			});
		},
		slider: function()
		{
			var slides = $('.img',$(this));
			var elems = slides.length;
			
			if(elems>0)
			{	
				// Add the active class
				$(slides[0]).addClass('active');
				
				// Only one image? No slider needed
				if(elems == 1)
				{
					$('.prev,.next',$(this)).remove();
				}
				else
				{
					// Set the navigation function
					var nav = function(dir)
					{
						// Get the current active element's position
						var current = 0;
						for(i=0;i<elems;i++)	
						{
							console.log($(slides[i]));
							if($(slides[i]).hasClass('active'))	
							{
								current = i;
								break;
							}
						}
						
						// Left
						if(dir == 'l')	
						{
							current--;
							if(current<0)current = elems-1;
						}
						// Right
						else
						{
							current++;
							if(current>elems-1)current = 0;
						}
						
						// Remove the "active" class from all the slides except the current one
						$.each(slides,function(k,v){
							$(v).removeClass('active');
							if(k == current) $(v).addClass('active');
						});
					};
					
					// Set the actions
					$('.prev,.next',$(this)).click(function(e){
						e.preventDefault();
						e.stopPropagation();
						if($(this).hasClass('prev'))
						{
							nav('l');
						}
						else
						{
							nav('r');
						}
					});
				}
			}
		},
		toggle: function(){
			$(this).click(function(e){
				e.preventDefault();
				e.stopPropagation();
				var button = $('.button',$(this)); 
				
				// Close
				if(button.hasClass('active'))	
				{
					// Deactivate
					button.removeClass('active');
					
					// Hide the text
					$(this).siblings('.image').children('.text').removeClass('active');
					
					// Show the images
					$(this).siblings('.image').children('.img').removeClass('hidden');
				}
				// Open
				else
				{
					// Activate
					button.addClass('active');
					
					// Show the text
					$(this).siblings('.image').children('.text').addClass('active');
					
					// Hide the images
					$(this).siblings('.image').children('.img').addClass('hidden');
				}
			});
		}
	});
	
	// Scrolled into view?
	$.fn.isiv = function(fnc,fnc2)
	{
		var isVisible = false;
		var elem = $(this);
		(function check(){
			setTimeout(function(){
				if($(elem).css('display') != 'none')
				{
					var docViewTop = $(window).scrollTop();
					var docViewBottom = docViewTop + $(window).height();
					if($(elem).offset() != null)
					{
						var elemTop = $(elem).offset().top;
						var elemBottom = elemTop + $(elem).height();			
						if((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) )
						{
							if(!isVisible)
							{
								isVisible = true;
								if(typeof fnc == 'function')
								{
									elem.fnc = fnc;elem.fnc();
								}
							}
						}
						else
						{
							if(isVisible)
							{
								isVisible = false;
								if(typeof fnc2 == 'function')
								{
									elem.fnc2 = fnc2;elem.fnc2();
								}
							}
							
						}
						check();
					}
				}
			},600);
		})();
	}
	
	// Define the Chromebox
	wp_octoms.toolbox.chromebox = function(h,c){
		// Get the post id
		var id = c.id;
		
		// Create the box
		if($('#cbox'+id).length == 0)
		{
			// Define the actions
			var actions = {
				"ok":function(e,c,h){return true;},
				"cancel":function(e,c,h){return false;}
			};
			
			// Get the content
			if(typeof c == 'object' && typeof c.data != 'undefined' && typeof c.url != 'undefined' && typeof c.rating != 'undefined')
			{
				// Set the title
				title = (typeof c.title == 'undefined')?"Chromium":c.title;
				
				// Initialize the buttons
				buttons = '';
				$.each(actions,function(k,v){t = k.charAt(0).toUpperCase();t = t + k.substr(1);buttons += '<div class="action unselectable" rel="'+k+'">'+t+'</div>';});
				
				// Add the element
				$('body').prepend('<div class="chromebox" id="cbox'+id+'"><div><div class="title unselectable"><a href="'+c.url+'" target="_blank">'+title+'</a>'+c.rating+'<div class="action close">x</div></div><div class="content"><iframe width=100% height=100% src="'+c.url+'"></iframe></div><div class="side-content"><div>'+c.data+'</div></div></div></div>');
				
				// Fade in
				var fervbox = $('body :first').fadeIn(600);	
				
				// Any action closes the window
				$('.action',fervbox).click(function(e){
					if(typeof actions[$(this).attr('rel')] != 'undefined')
					{
						actions[$(this).attr('rel')](e,c,h);
					}
					fervbox.fadeOut(500,function(){});
				});
				
				// Escape closes the window
				$(document).keydown(function(e){if(e.keyCode == 27) {fervbox.fadeOut(500,function(){});}});
			
				// Load the rating utility
				fervbox.find('.rating').rating();
			}
			else
			{
				// Try to return an error message
				if(typeof wp_octoms.alert != 'undefined')
				{
					wp_octoms.alert('Invalid server response. Please refresh and try again.',false);
				}
			}
		}
		// Box already created
		else
		{
			var fervbox = $('#cbox'+id).fadeIn(600);
		}
	};
	
	// Define the rating response
	wp_octoms.toolbox.rating_update = function(h,c)
	{
		if(typeof c.id != 'undefined' && typeof c.score != 'undefined')
		{
			var activate = function(no,el){
				el.children('div').removeClass('x');
				for(i=1;i<=no;i++)
				{
					el.children('div:nth-child('+i+')').addClass('x');
				}
			};
			$('.rating[for='+c.id+']').attr('score',parseInt(c.score));
			activate(parseInt(c.score),$('.rating[for='+c.id+']').children('.stars'));
		}
		else
		{
			wp_octoms.alert('Invalid server response. Please refresh and try again.',false);
		}
	}
	
	// Load the basic box utilities
	$.fn.extend({
		box: function(){
			$.each($(this),function(k,v){
				// Anchor action
				$(this).click(function(e){
					e.preventDefault();
					if($('#cbox'+$('span',$(this)).attr('id')).length == 0)
					{
						wp_octoms.xform({
							action:'get_post',
							data:{
								id:$('span',$(this)).attr('id')
							}
						},$('span',$(this)));
					}
					else
					{
						wp_octoms.toolbox.chromebox(null,{id:$('span',$(this)).attr('id')});
					}
				});
				
				// Load the rating utility for all page posts
				$('span > .rating',$(this)).rating();
				
				// Load the image slider utility
				$('span > .image',$(this)).slider();
				
				// Load the image toggling utility
				$('span > .toggle',$(this)).toggle();
				
			});
			return $(this);
		}
	});
	
	// Append posts
	wp_octoms.toolbox.append_page = function(h,c)
	{
		if(typeof c.status != 'undefined')
		{
			// Page found
			if(c.status == 'success')
			{
				if(typeof c.posts == 'object' && typeof c.page != 'undefined')
				{
					// Remove the "paged-*" class
					$('body')[0].className = $.trim($('body')[0].className.replace(/paged-[0-9]+/ig, ''));
					
					// Add the new page body class
					$('body').addClass('paged-'+c.page);
					
					// Append all the boxes
					$.each(c.posts,function(k,v){
						// Append the box
						$('.content .box-wrapper').append(v);
						
						// Add the functionality
						$('.content .box-wrapper > :last-child').
							box().
							css('opacity',0).
							animate(
								{opacity:1},
					            {queue:false, duration:1000, easing: 'swing'}
							);
					});
					
					// All done
					$('.loadmore').removeClass('active');
				}
				else
				{
					wp_octoms.alert('Invalid server response. Please refresh and try again.',false);
				}
			}
			// Page not found
			else
			{
				// Remove the "loadmore"
				$('.loadmore').fadeOut(function(){$(this).remove();});
				
			}
		}
		else
		{
			wp_octoms.alert('Invalid server response. Please refresh and try again.',false);
		}
	};
	
	
	// Load post chromebox
	$('.box-wrapper > div').box();
	
	// Load more?
	$('.loadmore').isiv(function(){
		// Get the page number
		match = $('body')[0].className.match(/paged-([0-9]+)/i);
		if (match != null) {
			page = match[1];
		} else {
			page = 1;
		}
		
		// Get the last box class
		match = $('.content .box-wrapper > :last-child').attr('class').match(/c([0-9]+)/i);
		if (match != null) {
			last = match[1];
		} else {
			last = 1;
		}
		
		// Activate the "loadmore" div
		if(!$('.loadmore').hasClass('active'))
		{
			$('.loadmore').addClass('active');
			
			// Get the page (server request)
			wp_octoms.xform({
				action:'get_page',
				data:{
					page:(parseInt(page)+1),
					last:(parseInt(last)+1)
				}
			},$(this));
		}
		
	},
	function(){
	});
	
	// Top menu functionality
	(function(){
		// Hide the elements
		$('#searchform, .menu-top-dropdown').css('display','none');
		
		// Click action
		$('.top-icon').click(function(){
			// Remove the active class, if set
			$('.top-icon').removeClass('active');
			
			var hide = function(e){
				$(e).animate(
					{opacity:0,width:0},
		            {queue:false, duration:1000, easing: 'swing',complete:function(){
			            	$(this).css('display','none');
			            }
		            }
				);
			};
			var show = function(e){
				$(e).css({display:'inline-block',width:0,opacity:0});
				$(e).animate(
					{opacity:1,width:200},
		            {queue:false, duration:1000, easing: 'swing'}
				);
			};
			
			// Menu click?
			if($(this).hasClass('for-menu'))
			{
				hide('#searchform');
				// Toggle Action
				if($('.menu-top-dropdown').css('display')=='none')
				{
					show('.menu-top-dropdown');
					$(this).addClass('active');
				}
				else
				{
					hide('.menu-top-dropdown');
					$(this).removeClass('active');
				}
				
			}
			// Search click?
			else
			{
				hide('.menu-top-dropdown');
				// Toggle Action
				if($('#searchform').css('display')=='none')
				{
					show('#searchform');
					$(this).addClass('active');
				}
				else
				{
					hide('#searchform');
					$(this).removeClass('active');
				}
			}	
		});
	})();
});